<template>
    <div class="trendCanPreference">
        <div class="loading-box" v-show="show">
            loading……
        </div>
        <div class="content-box">
            <div id="main" class="trendArea">

            </div>
            <div class="top-box">
                <div>
                    <span>Start:</span>
                    <el-date-picker v-model="form.startTime" type="datetime" placeholder="Please enter"
                        :disabled-date="disabledStartDate" :disabled="form.endTime && form.startTime > form.endTime"
                        @change="changeStartTime"></el-date-picker>
                </div>
                <div>
                    <!-- <el-button type="primary" size="small" v-if="!isEdit" @click="isEdit = !isEdit">Edit</el-button> -->
                    <el-button type="primary" size="small" @click="addFun">New Tag</el-button>
                    <el-button type="primary" size="small" @click="saveFun">Commit</el-button>
                    <el-button type="primary" size="small" @click="saveAsFun">Save as
                        Favorite</el-button>
                    <el-button type="primary" size="small" @click="openFavoriteList">Favorate List</el-button>
                </div>
                <div>
                    <span>End:</span>
                    <el-date-picker v-model="form.endTime" type="datetime" placeholder="Please enter"
                        :disabled="form.startTime && form.endTime < form.startTime" :disabled-date="disabledEndDate"
                        @change="changeEndTime"></el-date-picker>
                </div>
            </div>
            <el-table :data="storedConfigsData" style="width: 100%" border height="180">
                <el-table-column label="Color" align="center" width="130">
                    <template #default="scope">
                        <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
                            <!-- <div v-if="!isEdit || scope.$index != 0"
                                :style="{ background: scope.row.color, width: '60px', height: '20px', border: scope.row.color == '#ffffff' ? '1px solid #909399' : 'none' }">
                            </div> -->
                            <el-color-picker v-model="scope.row.color"></el-color-picker>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="trendName" label="Trend Name" align="center" width="270">
                    <template #default="scope">
                        <div v-if="!isEdit || scope.$index != 0">{{ scope.row.trendName }}</div>
                        <div v-if="isEdit && scope.$index == 0"><el-input v-model="scope.row.trendName"
                                placeholder="Please enter the content"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="tagName" label="Tag Name" align="center" width="270">
                    <template #header>
                        Tag Name
                    </template>
                    <template #default="scope">
                        <div v-if="!isEdit || scope.$index != 0">{{ scope.row.tagName }}</div>
                        <!-- productionid -->
                        <div v-if="isEdit && scope.$index == 0">
                            <!-- <el-select v-model="scope.row.tagName" allow-create filterable placeholder="Please select"
                                @change="(e) => tagNameChange(e, scope.$index)">
                                <el-option v-for="item in productionid" :key="item.tagName"
                                    :label="item.tagName + ' , ' + item.unit + ' , ' + item.remark"
                                    :value="item.tagName">
                                </el-option>
                            </el-select> -->
                            <el-select v-model="scope.row.tagName" filterable remote @focus="changelist"
                                :remote-method="handleRemoteMethod" :loading="loading" ref="select"
                                @change="(e) => tagNameChange(e, scope.$index)" placeholder="Please select"
                                popper-class="selectCls">
                                <div style="margin-left: 15px;font-size: 0.9rem;border-bottom: 1px solid #333;">Tag Name
                                    | Unit | Description</div>
                                <el-option v-for="item in productionid" :key="item.value" :label="item.label"
                                    :value="item.value">
                                    <span>{{ item.label }} {{ ' | ' + item.unit }} {{ ' | ' + item.desc }}</span>
                                </el-option>
                                <el-pagination small @current-change="handlePageChange" :current-page="currentPage"
                                    :page-size="pageSize" :total="filteredOptions.length" layout="prev, pager, next">
                                </el-pagination>
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="Unit" align="center" width="100">
                    <template #default="scope">
                        <div v-if="!isEdit || scope.$index != 0">{{ scope.row.unit }}</div>
                        <div v-if="isEdit && scope.$index == 0"><el-input v-model="scope.row.unit"
                                placeholder="Please enter the content"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="desc" label="Desc" align="center">
                    <template #default="scope">
                        <div v-if="!isEdit || scope.$index != 0">{{ scope.row.desc }}</div>
                        <div v-if="isEdit && scope.$index == 0"><el-input v-model="scope.row.desc"
                                placeholder="Please enter the content"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="axes" label="Axes" align="center" width="200" show-overflow-tooltip>
                    <template #default="scope">
                        <!-- <div v-if="!isEdit || scope.$index != 0">{{ scope.row.axes }}</div> -->
                        <div>
                            <el-select v-model="scope.row.axes" placeholder="Please select">
                                <el-option v-for="item in axesoOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="Review" align="center" width="100">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="confirmEvent(scope.row, scope.$index)">
                            Delete
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="saveDialogVisible" title="Create personal preferences" width="600px">
            <el-form label-width="120px">
                <el-form-item label="Name:">
                    <el-input v-model="likeName" placeholder="Please enter the content"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="saveDialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="onSavelick">Submit</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="favoriteDialogVisible" title="Favorite List" width="500px">
            <el-table :data="favoritaList" style="width: 100%" @row-dblclick="rowDbclickFun">
                <el-table-column prop="name" label="Name" width="150" />
                <el-table-column prop="updateTime" label="UpdateTime" width="180" />
                <el-table-column label="Operate" min-width="120" width="130">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="deleteClick(scope)">
                            Delete
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>

</template>
<script>
import * as echarts from "echarts";
import { getTrendTimeValueByTagName, getWellInfoProductionLast, getConfigList, saveConfig, getWellTag, getAllWellTag, getFavoriteList } from '@/api/index'
import { ElLoading } from 'element-plus'
import { convertBeijingToCalgary } from "@/utils/common.js"
import { nextTick } from "vue";
import CryptoJS from 'crypto-js';

// 子窗口的 JavaScript 代码
window.addEventListener('beforeunload', function () {
    // 尝试通过 postMessage 通知父窗口
    if (window.opener && !window.opener.closed) {
        try {
            window.opener.postMessage('window-closing', '*');
        } catch (e) {
            console.error('无法通过 postMessage 通知父窗口:', e);
        }
    }
});
export default {
    name: "TrendCanPreference",
    data() {

        return {
            show: false,
            form: {
                startTime: "",
                endTime: this.convertBeijingToCalgary(),
                tagName: ""
            },
            tagName: "",
            xData: [],
            dateList: [],
            valueList: [],
            dataListArray: [],
            totalLegend: [],
            lineColor: [
                '#fe7501', '#00d4fa', '#f371ff', '#4ad400', '#bb1504', '#31adf3', '#0345e3',
                '#9ce6fd', '#868ecb', '#f90aaf', '#f9cdd8',
                '#fc7298', '#5a91f5', '#b6e959', '#4ec4d6',
                '#fed505', '#f59f83', '#a00386', '#5b63ff', '#b29bc3', '#7de7a2', '#fec503'],
            myChart: "",
            dialogTableVisible: false,
            tableData: [],
            sortedDates: [],
            seriesList: [],
            legendGroup: [[], [], [], []],
            deleteTagName: '',//标记要删除的tagName
            doubleY: false,
            loading: false,
            timer: null,
            storedConfigsData: [],
            //6个新的根据单位
            unitList: [],
            isEdit: false,
            axesoOptions: [
                {
                    value: 'top left',
                    label: 'top left'
                },
                {
                    value: 'top right',
                    label: 'top right'
                },
                {
                    value: 'middle left',
                    label: 'middle left'
                },
                {
                    value: 'middle right',
                    label: 'middle right'
                },
                {
                    value: 'below left',
                    label: 'below left'
                },
                {
                    value: 'below right',
                    label: 'below right'
                },
            ],
            productionid: [],
            saveDialogVisible: false,
            likeName: '',
            likeId: '',
            isLikeId: false,
            filteredOptions: [],

            loadingSelect: false,
            currentPage: 1,
            apiTagsList: [],
            pageSize: 10,
            favoriteDialogVisible: false,
            favoritaList: [],
            routerData: {}

        }
    },
    created() {
        document.title = 'Tags-Trend';
        const SECRET_KEY = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6c7b8c9d0e1f2a3b4c5d6a7b8';
        const encryptedData = this.$route.query.data;
        const bytes = CryptoJS.AES.decrypt(encryptedData, SECRET_KEY);
        this.routerData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
        //初始化并存储起止时间
        this.initTime();

        if (localStorage.getItem('preferenceId') == null) {
            this.isLikeId = false
            this.checkWell()
            this.setTagName()

        } else {
            this.isLikeId = true
            this.getConfigList()
        }

    },

    mounted() {
        window.addEventListener("resize", this.handleChartResize);
    },
    watch: {
        tagName: {
            handler(newVal, oldVal) {
                if (newVal && newVal.length > 0) {
                    // this.getTrendTimeValueByTagNameFun(this.form)
                }
            }, immediate: true
        }
    },
    beforeUnmount() {
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
        if (this.myChart) {
            this.myChart.dispose()
        }
    },
    methods: {
        rowDbclickFun(e) {
            localStorage.setItem('preferenceId', e.id)
            localStorage.setItem('preferenceName', e.name)
            this.favoriteDialogVisible = false
            //初始化并存储起止时间
            this.initTime();
            if (localStorage.getItem('preferenceId') == null) {
                this.isLikeId = false
                this.checkWell()
                this.setTagName()

            } else {
                this.isLikeId = true
                this.getConfigList()
            }
            document.title = 'Tags-Trend';
        },
        //删除喜好
        deleteClick(e) {
            ElMessageBox.confirm(
                'Delete this preference?',
                'Delete',
                {
                    confirmButtonText: 'OK',
                    cancelButtonText: 'Cancel',
                    type: 'warning',
                }
            )
                .then(() => {
                    deleteFavorite([e.row.id]).then(res => {
                        if (res.code == 200) {
                            this.openFavoriteList()
                        }
                    })
                })
        },
        //打开喜好列表
        openFavoriteList() {
            this.favoriteDialogVisible = true
            getFavoriteList().then(res => {
                this.favoritaList = res.data
            })
        },



        changelist() {
            this.ground();
        },
        handleRemoteMethod(query) {
            if (query !== "") {
                this.loadingSelect = true;
                setTimeout(() => {
                    this.filteredOptions = this.apiTagsList.filter((item) =>
                        item.label.toLowerCase().includes(query.toLowerCase())
                    );
                    this.currentPage = 1; // Reset to first page
                    this.updatePaginatedOptions();
                    this.loadingSelect = false;
                }, 200);
            } else {
                this.filteredOptions = this.apiTagsList;
                this.currentPage = 1; // Reset to first page
                this.updatePaginatedOptions();
            }
        },
        updatePaginatedOptions() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = this.currentPage * this.pageSize;
            this.productionid = this.filteredOptions.slice(start, end);
        },
        handlePageChange(page) {
            this.currentPage = page;
            this.updatePaginatedOptions();
        },
        ground() {
            getAllWellTag().then((res) => {
                if (res.code === 200) {
                    const uniqueTags = new Set();
                    this.apiTagsList = res.data
                        .filter((item) => {
                            const tagName = item.tagName;
                            if (!uniqueTags.has(tagName)) {
                                uniqueTags.add(tagName);
                                return true;
                            }
                            return false;
                        })
                        .map((item) => ({
                            label: item.tagName,
                            value: item.tagName,
                            desc: item.remark,
                            unit: item.unit
                        }));
                    this.filteredOptions = this.apiTagsList;
                    this.currentPage = 1;
                    this.updatePaginatedOptions();
                }
            });
        },

        tagNameChange(e, index) {
            this.productionid.forEach(v => {
                if (v.value == e) {
                    this.storedConfigsData[index].trendName = v.label
                    this.storedConfigsData[index].unit = v.unit
                    this.storedConfigsData[index].desc = v.desc
                }
            });
        },
        handleBeforeUnload(event) {
            // 可以在这里执行一些清理操作
            // 如果需要提示用户确认关闭，可以设置 event.returnValue
            // 注意：现代浏览器可能不会显示自定义消息，只会显示默认提示
            event.preventDefault();
            event.returnValue = '您有未保存的更改，确定要离开吗？';
            return event.returnValue;
        },
        checkWell() {
            this.wellName = this.routerData.wellName;
            if (localStorage.getItem('wellName') == null) {
                localStorage.setItem('wellName', this.routerData.wellName)
            }
        },
        panduanUnit(unit) {
            this.unitList = this.getStorage('unitList') || []
            if (this.unitList.length < 6) {
                if (!this.unitList.includes(unit)) {
                    this.unitList.push(unit)
                }
            }
            this.setStorage('unitList', this.unitList)
            const index = this.unitList.indexOf(unit)
            if (index == -1) {
                return 'top left'
            } else if (index < 6) {
                return this.axesoOptions[index].value
            } else {
                return 'top left'
            }
        },
        setTagName() {
            if (this.routerData.key && this.routerData.key.length > 0) {
                this.form.tagName = this.routerData.key
                this.tagName = this.routerData.key
                const unit = this.routerData.unit
                const desc = this.routerData.desc
                let data = {
                    axes: this.panduanUnit(unit),
                    color: this.getRandomHexColor(),
                    trendName: this.tagName,
                    tagName: this.tagName,
                    unit: unit,
                    desc: desc
                }
                if (this.getStorage('dataList') === null) {
                    this.storedConfigsData = [];
                    this.storedConfigsData.push(data)
                } else {
                    this.storedConfigsData = this.getStorage('dataList')

                    const hasTag = this.storedConfigsData.some(item => item.tagName === this.tagName);
                    if (!hasTag) {
                        this.storedConfigsData.push(data)
                    }
                }
                this.localData(data)
                this.addAListToTheData(this.storedConfigsData)
            } else {
                this.addAListToTheData(this.storedConfigsData)
            }
        },
        //把数据保存到本地
        localData(data) {
            // 存储趋势图x轴坐标，(注意：此坐标会在时间改变后并执行搜索的时候进行重置)

            let found = null;
            // 存储图例
            if (this.getStorage('legend') === null) {
                let legend = [];
                legend.push(data.tagName);
                this.setStorage('legend', legend)
            } else {
                let legend = this.getStorage('legend')

                found = legend.find((item, index) => item === data.tagName);// 是否已存在

                if (!found) {
                    legend.push(data.tagName)
                    this.setStorage('legend', legend)
                }
            }

            //存储数据列表
            if (this.getStorage('dataList') === null) {
                let dataList = [];
                dataList.push(data)
                this.setStorage('dataList', dataList)
            } else {
                let dataList = this.getStorage('dataList')
                if (!found) {
                    dataList.push(data)
                    this.setStorage('dataList', dataList)
                }
            }

        },

        addFun() {
            if (!this.hasAnyEmptyProperty(this.storedConfigsData, ['axes', 'color', 'trendName', 'tagName'])) {
                this.storedConfigsData.unshift({
                    axes: 'top left',//不动
                    color: this.getRandomHexColor(),
                    trendName: '',
                    tagName: '',
                    unit: '',
                    desc: ''
                })
                this.isEdit = true
            } else {
                this.$message('Please check if any attributes are empty')
            }

        },
        //随机颜色生成
        getRandomHexColor() { 
            let dataList=this.getStorage('dataList')||[]
            if (dataList.length < 22) {
                return this.lineColor[dataList.length]
            } else {
                // 生成更鲜艳的 #RRGGBB 格式随机颜色
                // 生成鲜艳明亮的 #RRGGBB 格式随机颜色
                const r = Math.floor(Math.random() * 128) + 128; // 红色分量 128-255
                const g = Math.floor(Math.random() * 128) + 128; // 绿色分量 128-255
                const b = Math.floor(Math.random() * 128) + 128; // 蓝色分量 128-255

                // 转换为十六进制
                const toHex = (value) => value.toString(16).padStart(2, '0');
                return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
            }
        },
        hasAnyEmptyProperty(array, properties) {
            return array.some(obj =>
                properties.some(property =>
                    obj[property] === null ||
                    obj[property] === undefined ||
                    obj[property] === ""
                )
            );
        },
        saveFun() {
            if (this.isLikeId) {
                // 有id
                this.likeName = localStorage.getItem('preferenceName')
                this.likeId = localStorage.getItem('preferenceId')
                this.openSaveFun()
            } else {
                //没有id
                this.isEdit = false
                this.likeName = ''
                this.likeId = ''
                this.setStorage('dataList', this.storedConfigsData)
                let legend = []
                this.storedConfigsData.forEach(v => {
                    legend.push(v.tagName)
                })
                this.setStorage('legend', legend)
                this.addAListToTheData(this.storedConfigsData)
            }

        },
        saveAsFun() {
            //没有id
            this.likeName = ''
            this.likeId = ''
            this.openSaveAsFavoriteFun()
        },
        //打开保存弹框
        openSaveAsFavoriteFun() {
            // 保存的时候要保存弹出姓名
            if (!this.hasAnyEmptyProperty(this.storedConfigsData, ['axes', 'color', 'trendName', 'tagName'])) {
                this.isEdit = false
                // this.saveConfig(this.storedConfigsData)
                this.saveDialogVisible = true
            } else {
                this.$message('Please check if any attributes are empty')
            }
        },
        //打开保存弹框
        openSaveFun() {
            // 保存的时候要保存弹出姓名
            if (!this.hasAnyEmptyProperty(this.storedConfigsData, ['axes', 'color', 'trendName', 'tagName'])) {
                this.isEdit = false
                // this.saveConfig(this.storedConfigsData)
                // this.saveDialogVisible = true
                this.onSavelick()
            } else {
                this.$message('Please check if any attributes are empty')
            }
        },
        //点击保存
        onSavelick() {
            if (this.isLikeId == false) {
                let obj = {
                    "name": this.likeName,
                    "list": this.storedConfigsData
                }
                this.saveConfig(obj)
            } else {
                //编辑
                let obj = {
                    "name": this.likeName,
                    "list": this.storedConfigsData,
                    "id": this.likeId
                }
                this.saveConfig(obj)
            }
        },

        //保存配置信息
        async saveConfig(data) {
            let res = await saveConfig(data)
            if (res.code == 200) {
                this.$message.success('Successfully saved personal preferences')
                this.saveDialogVisible = false
                this.setStorage('dataList', this.storedConfigsData)
                let legend = []
                this.storedConfigsData.forEach(v => {
                    legend.push(v.tagName)
                })
                this.setStorage('legend', legend)

                this.addAListToTheData(this.storedConfigsData)
            } else {
                return this.$message.error(res.msg);
            }
        },
        //给数据添加列表
        async addAListToTheData(data) {
            this.dataListArray = []
            const promises = data.map(item => {
                this.form.tagName = item.tagName
                return this.getTrendTimeValueByTagNameFun(this.form, item);
            });
            try {
                await Promise.all(promises);
                // 所有异步操作都完成后的回调
                const normalObject = JSON.parse(JSON.stringify(this.dataListArray));
                this.getLocationDataInitChart(normalObject)
            } catch (error) {
                console.error('An error occurred while fetching trends:', error);
            }
        },
        //获取列表信息-（现在得有id的时候获取了）
        async getConfigList() {
            let res = await getConfigList({ id: localStorage.getItem('preferenceId') })
            this.storedConfigsData = []
            const tagName = this.routerData.key
            const unit = this.routerData.unit
            const desc = this.routerData.desc
            if (tagName != undefined && unit != undefined && desc != undefined) {
                if (res.code == 200) {
                    // this.storedConfigsData = res.data
                    this.storedConfigsData = this.getStorage('dataList')
                    const hasTag = this.storedConfigsData.some(item => item.tagName === tagName);
                    if (!hasTag) {
                        let data = {
                            axes: this.panduanUnit(unit),
                            color: this.getRandomHexColor(),
                            trendName: tagName,
                            tagName: tagName,
                            unit: unit,
                            desc: desc
                        }
                        //当前数据里没有此条，要添加并且保存
                        this.storedConfigsData.push(data)
                        this.localData(data)
                        this.addAListToTheData(this.storedConfigsData)
                    } else {
                        //否则直接进行下一步请求渲染
                        this.addAListToTheData(this.storedConfigsData)
                    }
                }
            } else {
                if (res.code == 200) {
                    this.storedConfigsData = res.data
                    this.setStorage('dataList', this.storedConfigsData)
                    let legend = []
                    this.storedConfigsData.forEach(v => {
                        legend.push(v.tagName)
                    })
                    this.setStorage('legend', legend)

                    //否则直接进行下一步请求渲染
                    this.addAListToTheData(this.storedConfigsData)

                }
            }

        },


        confirmEvent(row, index) {
            if (index == 0) {
                this.isEdit = false
            }
            this.storedConfigsData.forEach((item, index) => {
                if (item.tagName === row.tagName) {
                    this.storedConfigsData.splice(index, 1)
                }
            })
        },
        //给每一条的数据添加数据列表
        async getTrendTimeValueByTagNameFun(params, data) {
            let res = await getTrendTimeValueByTagName(params)
            if (res.code !== 200) {
                this.show = false
                return this.$message.error(res.msg);
            } else {
                // 结果不为空对象
                if (JSON.stringify(res.data) === '{}') {
                    this.show = false;
                    return this.$message.warning("no data")
                } else {
                    this.dataListArray.push({
                        axes: data.axes,
                        color: data.color,
                        trendName: data.trendName,
                        tagName: data.tagName,
                        timeList: res.data.timeList,
                        valueList: res.data.valueList
                    })
                    this.xData = res.data.timeList
                    const normalObject = JSON.parse(JSON.stringify(this.dataListArray));
                    this.getLocationDataInitChart(normalObject)
                }

            }
        },
        getLocationDataInitChart(normalObject) {
            let dataList = normalObject//需要把这里改成实时查询
            let xData = this.xData
            let legendGroup = [[], [], [], []];
            let seriesList = [];


            dataList.forEach((item, i) => {
                if (item.axes === 'top left') {
                    legendGroup[0].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                        gridIndex: 0
                    })
                } else if (item.axes === 'top right') {

                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 1,
                        gridIndex: 0
                    })
                } else if (item.axes === 'middle left') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 1,
                        yAxisIndex: 2,
                        gridIndex: 1
                    })
                } else if (item.axes === 'middle right') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 1,
                        yAxisIndex: 3,
                        gridIndex: 1
                    })
                }
                else if (item.axes === 'below left') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 2,
                        yAxisIndex: 4,
                        gridIndex: 2
                    })
                }
                else if (item.axes === 'below right') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 2,
                        yAxisIndex: 5,
                        gridIndex: 2
                    })
                } else {
                    legendGroup[0].push(item.tagName)
                    seriesList.push({
                        name: item.trendName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                        gridIndex: 0
                    })
                }
            })
            this.myChart = this.initEcharts(xData, seriesList, legendGroup)
        },
        handleChartResize() {
            if (!this.myChart) {
                return;
            }
            this.myChart.resize();
        },
        createGrid(top, height) {
            return {
                left: "60px",
                right: "60px",
                top: top,
                bottom: '15%',
                height: height
            };
        },
        getGridConfig(setChart) {
            const gridConfigs = {
                '0': [
                    this.createGrid("3%", "86%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("89%", "0%")
                ],
                '1': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("3%", "86%"),
                    this.createGrid("89%", "0%")
                ],
                '2': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("3%", "86%")
                ],
                '01': [
                    this.createGrid("3%", "39%"),
                    this.createGrid("45%", "45%"),
                    this.createGrid("89%", "0%")
                ],
                '12': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("3%", "42%"),
                    this.createGrid("47%", "43%")
                ],
                '02': [
                    this.createGrid("3%", "42%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("47%", "43%")
                ],
                '012': [
                    this.createGrid("3%", "27%"),
                    this.createGrid("33%", "27%"),
                    this.createGrid("63%", "27%")
                ]
            };

            if (setChart.length === 1) {
                const element = setChart[0].toString();
                return gridConfigs[element] || [];
            } else if (setChart.length === 2) {
                const elements = setChart.sort().join('');
                return gridConfigs[elements] || [];
            } else if (setChart.length === 3) {
                return gridConfigs['012'] || [];
            }
            return [];
        },
        initEcharts(xData, seriesList, legendGroup) {
            var chartDom = document.getElementById('main');
            var myChart = echarts.init(chartDom);
            myChart.clear();
            var grid = []
            var option;
            let chart = []
            seriesList.forEach(v => {
                chart.push(v.gridIndex)
            })
            let setChart = [...new Set(chart)]
            grid = this.getGridConfig(setChart);

            option = {
                tooltip: {
                    trigger: 'axis',// 使用坐标轴触发，而不是数据项触发。这样可以显示所有系列的数据。
                    formatter: function (params) {
                        let str = '<div style="display:flex;align-items: flex-start;font-size:0.8rem;">' + params[0].name + '</div>';
                        str += ''
                        let num = ''
                        params.forEach((item) => {
                            if (item.axisIndex != num && num !== '') {
                                //加线
                                str += `<div style=" border-bottom: 1px solid #fff;"></div>`
                            }
                            num = item.axisIndex
                            if (item.seriesName !== "Warning") {
                                str += `<div style="display:flex;align-items: center;"><div style="display:flex;align-items: center;"><div style="width:0.5rem;height:.5rem;background:${item.color}; border-radius: 1rem;margin-top:0.1rem;margin-right:0.3rem;"></div><span style="font-size:0.8rem;">${item.seriesName}：</span></div><div><span style="font-size:0.8rem;">${item.data}</span> </div></div>`
                            }
                        })
                        return str;
                    },
                    textStyle: {
                        color: "rgba(255, 255, 255, 1)",
                        align: "left"
                    },
                    backgroundColor: "rgba(0,0,0,0.8)",
                    borderColor: "rgba(219, 230, 255, 0.8)"
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 0,
                        show: false,
                        axisLabel: {
                            inside: false,
                            textStyle: {
                                fontSize: '10',
                                itemSize: ''
                            }
                        },

                    },
                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 1,
                        show: false,
                        axisLabel: {
                            inside: false,
                            textStyle: {
                                fontSize: '10',
                                itemSize: ''
                            }
                        },
                    },
                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 2,
                        show: true,
                        axisLabel: {
                            inside: false,
                            textStyle: {
                                fontSize: '10',
                                itemSize: ''

                            }
                        },
                    }
                ],

                yAxis: [
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 0,
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                        // scale: true, //自适应
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 0,
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 1,
                        top: '35%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 1,
                        top: '35%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 2,
                        top: '80%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 2,
                        top: '80%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                ],
                axisPointer: {
                    link: [
                        {
                            xAxisIndex: 'all'
                        }
                    ],
                    animation: false
                },
                grid: grid,
                series: seriesList,
                dataZoom: [
                    {
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        height: 12,
                        textStyle: {
                            color: "#fff",
                            fontSize: '0.7rem'
                        },
                        showDataShadow: false,
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        showDataShadow: false,
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        showDataShadow: false,
                    },
                ],
            };

            option && myChart.setOption(option);
            // 监听窗口大小改变事件
            window.addEventListener('resize', function () {
                myChart.resize();
            });
            this.show = false;
            return myChart
        },
        // ----------------------------------------------
        initTime() {
            let endTime = "";
            if (this.isDateObject(this.form.endTime)) {
                endTime = this.formatDate(this.form.endTime);
            } else {
                endTime = this.form.endTime;
            }
            this.calculateTime(endTime, "day14", "0");
        },
        isDateObject(value) {
            return value instanceof Date;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date
                .getDate()
                .toString()
                .padStart(2, "0");
            const hours = date
                .getHours()
                .toString()
                .padStart(2, "0");
            const minutes = date
                .getMinutes()
                .toString()
                .padStart(2, "0");
            const seconds = date
                .getSeconds()
                .toString()
                .padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        calculateTime(timeString, unit, type) {
            const time = new Date(timeString);
            const step = {
                hour: 28800000, // 8小时
                day: 86400000, // 一天
                day7: 604800000, // 一天
                day14: 1209600000, // 一天
                day30: 2592000000, // 一天
                day60: 5184000000 // 一天
            };
            if (type == "0") {
                // 减 计算startTime
                const newTime = new Date(time.getTime() - step[unit]);
                this.form.startTime = this.formatDate(newTime);
                localStorage.setItem('startTime', this.formatDate(newTime))
            } else {
                // 加 计算endtime
                const newTime = new Date(time.getTime() + step[unit]);
                this.form.endTime = this.formatDate(newTime);
            }
        },
        // 将北京时间转换为卡尔加里时间
        convertBeijingToCalgary(beijingDate) {
            const options = {
                timeZone: 'America/Edmonton',  // 卡尔加里所属时区
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false                 // 强制24小时制
            };

            // 直接生成目标格式的字符串
            const formatter = new Intl.DateTimeFormat('en-CA', options);
            const calgaryTime = formatter.format(new Date())
                .replace(/(\d{4})-(\d{2})-(\d{2}),? (\d{2}:\d{2}:\d{2})/, '$1-$2-$3 $4');
            return calgaryTime
        },
        disabledStartDate(time) {
            if (this.form.endTime) {
                return time.getTime() > new Date(this.form.endTime).getTime();
            } else {
                return time.getTime() > convertBeijingToCalgary();
            }

        },
        disabledEndDate(time) {
            if (this.form.startTime) {
                return time.getTime() < new Date(this.form.startTime).getTime() || time.getTime() > convertBeijingToCalgary();
            } else {
                return time.getTime() > convertBeijingToCalgary();
            }
        },

        changeStartTime(item) {
            const date = new Date(item);
            const year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let hours = date.getHours();
            let minutes = date.getMinutes();
            let seconds = date.getSeconds();
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            hours = hours < 10 ? '0' + hours : hours;
            minutes = minutes < 10 ? '0' + minutes : minutes;
            seconds = seconds < 10 ? '0' + seconds : seconds;
            this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            localStorage.setItem('startTime', this.form.startTime)
            if (this.form.endTime && this.form.startTime > this.form.endTime) {
                this.form.startTime = this.form.endTime;
                localStorage.setItem('startTime', this.form.startTime)
            }
            this.addAListToTheData(this.storedConfigsData)
        },
        changeEndTime(value) {
            this.form.endTime = this.formatDate(value)
            if (this.form.startTime && this.form.endTime < this.form.startTime) {
                this.form.endTime = this.form.startTime;
            }
            localStorage.setItem('endTime', this.form.endTime)
            this.addAListToTheData(this.storedConfigsData)
        },
        setStorage(key, data) {
            localStorage.setItem(key, JSON.stringify(data))
        },
        getStorage(key) {
            return JSON.parse(localStorage.getItem(key))
        },
    }
}
</script>
<style>
.selectCls {
    height: 390px;

    .el-scrollbar__wrap {
        overflow: visible;

    }

    .el-scrollbar__thumb {
        display: none;
    }
}
</style>
<style scoped lang="scss">
.loading-box {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    font-size: 1rem;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgb(0, 0, 0, 0.6);
    z-index: 100;
    color: #ffffff;
}

.custom-loading {
    z-index: 1500;
    /* 或者比你想要的 Dialog 的 z-index 低一些 */
}

.trendCanPreference {
    width: 100vw;
    height: 100vh;

    .header-box {
        background: url("@/assets/header_bg.png") no-repeat;
        background-position: center center;
        height: 5h;
        font-size: 1.8rem;
        padding-top: 0.5rem;
        color: rgb(17, 137, 229);
    }

    .top-box {
        padding-top: 1vh;
        height: 3vh;
        display: flex;
        justify-content: space-between;
        margin-top: -20px;
        width: 100%;

        ::v-deep .el-input__wrapper {
            background-color: rgba(255, 0, 0, 0);
            border-radius: 0px;
            box-shadow: 0 0 0 0.0625rem #00000000;
        }

        ::v-deep .el-input__wrapper:hover {
            box-shadow: 0 0 0 0.0625rem #00000000;
        }

        ::v-deep .el-input__inner {
            color: white;
        }

        span {
            padding-left: 1vw;
            padding-right: 0.2vw;
            color: #eeeeee;
        }
    }

    .content-box {
        height: 94vh;
        padding: 10px;

        .dialog-content {

            //border: 1px solid #ff0000;
        }
    }

    .ml-1 {
        margin-left: 1vw;
    }

    .trendArea {
        width: 100%;
        height: 78vh;
    }
}
</style>